(function(){
  const CFG = window.SURPRISE_CONFIG || {};
  const TIPS = CFG.tips || [];
  const CARD_COLORS = CFG.cardColors || ['#ffe4ec','#fff0f5','#ffe4e1','#fff5ee'];
  const IS_MOBILE = window.innerWidth < 768;
  const SPEED = IS_MOBILE ? (CFG.speedMobile||160) : (CFG.speedDesktop||120);
  const TOTAL = CFG.totalWindows || 150;

  // Apply gradient
  document.documentElement.style.setProperty('--bg-gradient', CFG.gradient || "linear-gradient(135deg,#ffeef8,#ffe8f0)");

  function $(id){ return document.getElementById(id); }

  function updateCounter(n){ $('counter').textContent = n; }

  function createTipBox(counter){
    const tip = TIPS[Math.floor(Math.random()*TIPS.length)] || "你真好看~";
    const color = CARD_COLORS[Math.floor(Math.random()*CARD_COLORS.length)];
    const box = document.createElement('div');
    box.className = 'tip-box';
    box.style.backgroundColor = color;
    box.setAttribute('role','note');

    const boxWidth = IS_MOBILE ? 130 : 140;
    const boxHeight = IS_MOBILE ? 38 : 40;
    const maxX = Math.max(5, window.innerWidth - boxWidth - 10);
    const maxY = Math.max(5, window.innerHeight - boxHeight - 10);
    const x = Math.max(5, Math.random()*maxX);
    const y = Math.max(5, Math.random()*maxY);
    box.style.left = x + 'px';
    box.style.top = y + 'px';

    const btn = document.createElement('button');
    btn.className = 'close-btn';
    btn.setAttribute('aria-label','关闭');
    btn.textContent = '×';
    btn.addEventListener('click', () => {
      const p = btn.parentElement;
      if (p && p.parentElement) p.parentElement.removeChild(p);
      counter.count = Math.max(0, counter.count - 1);
      updateCounter(counter.count);
    });

    const text = document.createElement('span');
    text.textContent = tip;
    box.appendChild(btn); box.appendChild(text);

    makeDraggable(box);
    document.body.appendChild(box);
    counter.count += 1; updateCounter(counter.count);
  }

  function makeDraggable(el){
    let pos1=0,pos2=0,pos3=0,pos4=0;
    function dragStart(e){
      const t = e.type==='touchstart'? e.touches[0] : e;
      e.preventDefault();
      el.style.zIndex = (parseInt(el.style.zIndex||'1000',10)+1).toString();
      pos3 = t.clientX; pos4 = t.clientY;
      document.addEventListener('mouseup', dragEnd);
      document.addEventListener('touchend', dragEnd);
      document.addEventListener('mousemove', dragMove);
      document.addEventListener('touchmove', dragMove, {passive:false});
    }
    function dragMove(e){
      const t = e.type==='touchmove'? e.touches[0] : e;
      e.preventDefault();
      pos1 = pos3 - t.clientX; pos2 = pos4 - t.clientY;
      pos3 = t.clientX; pos4 = t.clientY;
      const nextTop = el.offsetTop - pos2;
      const nextLeft = el.offsetLeft - pos1;
      const w = el.offsetWidth||140, h = el.offsetHeight||40;
      el.style.top = Math.min(Math.max(0,nextTop), window.innerHeight - h) + 'px';
      el.style.left = Math.min(Math.max(0,nextLeft), window.innerWidth - w) + 'px';
    }
    function dragEnd(){
      document.removeEventListener('mouseup', dragEnd);
      document.removeEventListener('touchend', dragEnd);
      document.removeEventListener('mousemove', dragMove);
      document.removeEventListener('touchmove', dragMove);
    }
    el.addEventListener('mousedown', dragStart);
    el.addEventListener('touchstart', dragStart, {passive:false});
  }

  async function startSurprise(){
    const audio = $('bgm');
    try {
      audio.muted = !CFG.music ? true : !!CFG.music.autoplayMuted;
      // ensure play attempt
      await audio.play();
      // if autoplayMuted false, unmute after user action in iOS when they click
    } catch(e){ /* ignore */ }
    updateMusicUI();

    $('welcomeMsg').style.display = 'none';
    $('controlPanel').style.display = 'block';

    const counter = {count: 0};
    for(let i=0;i<TOTAL;i++){
      createTipBox(counter);
      await new Promise(r=>setTimeout(r,SPEED));
    }
  }

  function clearAll(){
    document.querySelectorAll('.tip-box').forEach(el=>el.remove());
    updateCounter(0);
  }

  function updateMusicUI(){
    const audio = $('bgm');
    $('musicState').textContent = audio.muted ? '已静音' : (audio.paused ? '暂停' : '播放中');
  }

  function buildHero(){
    const title = CFG.title || '💕 小惊喜 💕';
    const name = CFG.showNameInTitle && CFG.name ? ` ${CFG.name} ` : '';
    $('heroTitle').textContent = title.replace('💕', '💕'); // keep emoji
    $('heroSubtitle').textContent = CFG.subtitle || '这是专属于你的心意';

    const lines = Array.isArray(CFG.heroLines) ? CFG.heroLines : [];
    $('heroLines').innerHTML = lines.map(l => `<div>${l}</div>`).join('');
  }

  // bind UI
  window.addEventListener('load', function(){
    // gradient
    document.body.style.background = getComputedStyle(document.documentElement).getPropertyValue('--bg-gradient');
    buildHero();
    updateCounter(0);
    updateMusicUI();

    // music button
    $('musicToggle').addEventListener('click', async function(){
      const audio = $('bgm');
      if (audio.paused) { try { await audio.play(); } catch(e){} }
      audio.muted = !audio.muted;
      updateMusicUI();
    });

    // start button
    $('startBtn').addEventListener('click', startSurprise);

    // clear button
    $('clearBtn').addEventListener('click', clearAll);
  });
})();